package com.wu.flandre_api.components;

import com.wu.flandre_common.entity.RpcRequest;
import com.wu.flandre_common.entity.RpcResponse;
import com.wu.flandre_api.components.netty.NettyClientHandler;
import com.wu.flandre_api.components.netty.RpcDecoder;
import com.wu.flandre_api.components.netty.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * NettyClientComponent <br/>
 *
 * @author 50816 <br/>
 * @date 2019/12/22 14:55 <br/>
 */
@Slf4j
public class NettyClientComponent {

    private final String host;
    private final int port;

    public NettyClientComponent(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        final EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        // 使用NioSocketChannel来作为连接用的channel类
        bootstrap.group(group).channel(NioSocketChannel.class)
                // 绑定连接初始化器
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //编码request
                        pipeline.addLast(new RpcEncoder(RpcRequest.class));
                        //解码response
                        pipeline.addLast(new RpcDecoder(RpcResponse.class));
                        //客户端处理类
                        pipeline.addLast(new NettyClientHandler());
                    }
                });
        //发起异步连接请求，绑定连接端口和host信息
        final ChannelFuture future = bootstrap.connect(host, port).sync();

        future.addListener((ChannelFutureListener) arg0 -> {
            if (future.isSuccess()) {
                log.info("连接Flandre引擎成功,address:{}", host + ":" + port);
            } else {
                log.error("连接Flandre引擎失败");
                future.cause().printStackTrace();
                group.shutdownGracefully(); //关闭线程组
            }
        });
        ChannelUtil.getInstance().setChannel(future.channel());
    }
}
